package com.springfreemwork.tomcat.servlet;

import com.alibaba.fastjson.JSON;
import com.springfreemwork.properties.ServerProperties;
import org.yaml.snakeyaml.Yaml;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

public class DemoServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	public void doGet(HttpServletRequest request,
					  HttpServletResponse response)
			throws IOException, ServletException {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE html><html>");
		out.println("<head>");
		out.println("<meta charset='UTF-8 />");
		out.println("<title></title>");
		out.println("</head>");
		out.println("<body bgcolor='white'>");
		out.println("<h1> wangle spring boot demo test</h1>");
		out.println("</body>");
		out.println("</html>");
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {

		// 设置内容类型为JSON
		response.setContentType("application/json");
		// 设置字符编码为UTF-8
		response.setCharacterEncoding("UTF-8");
		// 获取PrintWriter对象用于写入响应
		PrintWriter out = response.getWriter();

		BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream()));
		StringBuilder jsonBuilder = new StringBuilder();
		String line;
		while ((line = reader.readLine()) != null) {
			jsonBuilder.append(line);
		}
		// 写入JSON数据
		out.print(jsonBuilder.toString());
		// 清空缓冲区，发送数据到客户端
		out.flush();
		// 关闭Writer对象
		out.close();

	}

	public static void main(String[] args) throws Exception{
		InputStream inputStream = DemoServlet.class.getResourceAsStream("/application.yml");

		Yaml yaml = new Yaml();
		Map<String, Object> data = yaml.load(inputStream);
		ServerProperties serverProperties = JSON.parseObject(JSON.toJSONString(data), ServerProperties.class);
		// 使用读取到的数据进行相应操作
		// 例如打印所有的键值对
		System.out.println(JSON.toJSONString(serverProperties));


	}
}
